package com.baiyinet.util.task;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.baiyinet.rest.CustomTrust;
import com.baiyinet.rest.UnSafeHostnameVerifier;
import com.baiyinet.util.Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;

/**
 * Created by developer on 17-10-19.
 */

public class SingleDownloadImageTask extends AsyncTask<String, Void, Boolean> {

    private static final String SAVE_PATH = Environment.getExternalStorageDirectory() + "/商品图片/";

    private Context mContext;

    private CustomTrust mCustomTrust;

    private String mHintStr;

    private String mUrl;

    private ProgressDialog mProgressDialog;

    public SingleDownloadImageTask(Context context, String hintStr) {

        this.mContext = context;
        this.mHintStr = hintStr;
        mCustomTrust = new CustomTrust(context);

    }

    /**
     * 表示任务执行之前的操作
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (mProgressDialog == null) {
            // in standard case YourActivity.this
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setMessage("下载中…");
            mProgressDialog.show();
        }
    }

    @Override
    protected Boolean doInBackground(String... params) {
        // 使用网络连接类下载网络数据
        mUrl = params[0];
        try {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            httpClientBuilder
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS);

            if (!TextUtils.isEmpty(mUrl) && mUrl.startsWith("https")) {
                // 添加https
                httpClientBuilder
                        .sslSocketFactory(mCustomTrust.sslSocketFactory, mCustomTrust.trustManager)
                        .hostnameVerifier(new UnSafeHostnameVerifier());
            }

            OkHttpClient httpClient = httpClientBuilder.build();
            Request request = new Request.Builder().url(mUrl).build();
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                InputStream is = response.body().byteStream();
                return downloadAction(is);
            } else {
                Timber.e(response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private boolean downloadAction(InputStream is) {
        if(!Utils.Network.isNetworkAvailable()){
            return false;
        }
        String fileName = System.currentTimeMillis() + "";

        try {
            String fileExt = Utils.getFileExtensionFromUrl(Uri.parse(mUrl).getLastPathSegment()).toLowerCase();

            saveInputStream(readStream(is),fileName + "." + fileExt);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        super.onPostExecute(success);
        try{
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
        }catch(Exception exception){
            exception.printStackTrace();
        }

        if(success) {
            Utils.UI.showToastShort("图片已保存到SD存储卡的\"商品图片\"目录");
        }else {
            Utils.UI.showToastShort("图片保存失败");
        }

    }


    public byte[] readStream(InputStream inStream) throws Exception{
        //把数据读取存放到内存中去
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len=inStream.read(buffer)) != -1){
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }

    public void saveInputStream(byte[] is, String fileName) {
        File saveFileDir = new File(SAVE_PATH);
        if(!saveFileDir.exists()) {
            saveFileDir.mkdirs();
        }

        File f = new File(SAVE_PATH, fileName);
        if (f.exists()) {
            f.delete();
        }

        try {
            FileOutputStream out = new FileOutputStream(f);
            out.write(is);
            out.flush();
            out.close();

            Uri uri = Uri.fromFile(f);
            if (Build.VERSION.SDK_INT > 23) {
//                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), f.getAbsolutePath(), "", "");
//                mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, f.getAbsolutePath());
                mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            }else {
                // 发送相册广播
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(uri);
                mContext.sendBroadcast(intent);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
